package com.imooc.user.thrift;

import com.imooc.thrift.user.UserService;
import org.apache.thrift.TProcessor;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.protocol.TJSONProtocol;
import org.apache.thrift.server.TNonblockingServer;
import org.apache.thrift.server.TServer;
import org.apache.thrift.transport.TFramedTransport;
import org.apache.thrift.transport.TNonblockingServerSocket;
import org.apache.thrift.transport.TTransportException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import java.net.Socket;

/**
 * <p>
 * thrift 的配置和启动
 * </p>
 *
 * @author gobigg
 * @since 2019/9/24
 */
@Configuration
public class ThriftServer {
    @Value("${service.port}")
    private int servicePort;
    @Autowired
    private UserService.Iface userSercce;


    @PostConstruct
    public void startThriftServer() {
        // 初始化处理器
        TProcessor processor = new UserService.Processor<>(userSercce);
        /**
         * 创建一个网络
         * thrift 的几种网络模式
         * 单线程
         * 线程池
         * NIO 的
         */
        //创建
        TNonblockingServerSocket socket = null;
        try {
            socket = new TNonblockingServerSocket(servicePort);
        } catch (TTransportException e) {
            e.printStackTrace();
        }
        TNonblockingServer.Args args = new TNonblockingServer.Args(socket);
        args.processor(processor);
        args.transportFactory(new TFramedTransport.Factory());
        /**  传输方式
         *    TBinaryProtocol 二进制
         *    TJSONProtocol json
         *    TCompactProtocol
         */
        args.protocolFactory(new TBinaryProtocol.Factory());

        //构建 server
        TServer server = new TNonblockingServer(args);
        server.serve();
    }
}
